<template>
  <view>
    <!-- 头部导航栏 -->
    <view class="top-navigate bg-white" style="padding: 53px 10px 20px 10px;">
      <view class="content cuIcon-back text-xl top-navigate-title" @click="goBack">
      </view>
      <view class="text-xl top-navigate-title">导航</view>
    </view>
    <!-- 地图区域 -->
    <view class="page">
      <unicloud-map ref="map" :debug="false" loadtime="auto" collection="opendb-poi" :where="where" :width="750"
        :height="heightCom" :scale="25" :poi-maximum="100" :default-icon="defaultIcon" :custom-icons="customIcons"
        :enable-scroll="true" :enable-zoom="true" :show-compass="true" :show-location="true">
      </unicloud-map>
    </view>
    <!-- 订单地址定位信息区域 -->
    <view class="addressInfo">
      <!-- 代取送 -->
      <view class="order-detail border-top" v-if="orderInfo.type==='代取送'">
        <view class="order-detail-title text-df ">物品类型: <text class="text-gray"
            style="margin-left: 20px;">{{orderInfo.goodsInfo.goodsType}}</text> </view>
        <view class="order-detail-title text-df ">物品重量: <text class="text-gray"
            style="margin-left: 20px;">{{orderInfo.goodsInfo.goodsWeight}}kg</text></view>
        <view class="order-detail-title text-df ">跑腿距离: <text class="text-gray"
            style="margin-left: 20px;">{{orderInfo.distance}}</text>
        </view>
        <view class="order-detail-title text-df ">备注: <text class="text-gray"
            style="margin-left: 20px;">{{orderInfo.note}}</text>
        </view>
      </view>

      <!-- 图片显示区域 -->
      <view class="cu-form-group" v-if="imgList.length>0">
        <view class="grid col-4 grid-square flex-sub">
          <view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="item">
            <image :src="item" mode="aspectFill" style="position: absolute;left:0"></image>
          </view>
        </view>
      </view>
      <view class="item_box" v-if="orderInfo.type==='代购'">
        商品:
        <view class="address">
          {{orderInfo.goodsInfo.goodsDetail}}
        </view>
      </view>
      <view class="item_box" v-if="orderInfo.shopAddress.address">
        指定店铺:
        <view class="address" @click="switchAddress(orderInfo.shopAddress)">
          {{orderInfo.shopAddress.address}}
        </view>
        <button class="cu-btn round shadow bg-green" :class="typeColor" style="width:70px ;"
          @click="goToNav(orderInfo.shopAddress)">
          导航
        </button>
      </view>

      <view class="item_box" v-if="orderInfo.pickAddress">
        取件 ：
        <view class="address" @click="switchAddress(orderInfo.pickAddress)">
          {{orderInfo.pickAddress.address}}
        </view>
        <button class="cu-btn round shadow bg-green" :class="typeColor" style="width:70px ;"
          @click="goToNav(orderInfo.pickAddress)">
          导航
        </button>
      </view>

      <view class="item_box" v-if="orderInfo.deliveryAddress">
        收货：
        <view class="address" @click="switchAddress(orderInfo.deliveryAddress)">
          {{orderInfo.deliveryAddress.address}}
        </view>
        <button class="cu-btn round shadow bg-green" :class="typeColor" style="width:70px ;"
          @click="goToNav(orderInfo.deliveryAddress)">
          导航
        </button>
      </view>

      <view class="item_box" v-if="!order.finished">
        <button class="cu-btn round shadow bg-orange" :class="typeColor" style="width:50% ;"
          @click="updateOrderStatus()">
          已取货
        </button>
        <button class="cu-btn round shadow bg-green" :class="typeColor" style="width:50% ;"
          @click="updateOrderFinished()">
          已送达
        </button>
      </view>
    </view>
  </view>
</template>

<script>
  import amap from '@/helper/amap-wx.130.js'
  import {
    mapState,
    mapMutations,
    mapActions
  } from 'vuex'
  var timer;
  const uniMapCo = uniCloud.importObject('uni-map-co', {
    customUI: true
  });
  import getCurrentDateTime from '../../utils/currentTime.js'
  const db = uniCloud.database();
  const _ = db.command;
  const category = "dynamics-001";
  export default {
    data() {
      return {
        //骑手当前位置信息
        runnerAddress: {},
        addressEnd: {},
        amapPlugin: null,
        orderInfo: {},
        order: [],
        id: '',
        key: '395d7dee752cc1f00bfee27142e41f85',
        where: {
          category: category
        },
        imgList: [],
        defaultIcon: "/static/icon/logo.png", // 默认图标
        // 自定义图标
        customIcons: [{
            type: "配送员",
            icon: "/static/icon-3service/buy.png"
          },
          {
            type: "目的地",
            icon: "/static/icon-3service/buy.png"
          }
        ],
        isStart: false,
        polyline: [],
        isReady: false,
        index: -1,
      }
    },
    onLoad(options) {
      this.amapPlugin = new amap.AMapWX({
        key: this.key
      });
      console.log('options', JSON.parse(options.order));
      this.order = JSON.parse(options.order)
      this.orderInfo = this.order.orderInfo;
      this.id = JSON.parse(options.order)._id;
      this.addressEnd = {
        latitude: this.orderInfo.deliveryAddress.latitude,
        longitude: this.orderInfo.deliveryAddress.longitude,
        name: this.orderInfo.deliveryAddress.name
      };
      //获取位置信息
      // console.log('2323', this.runnerAddress.latitude && this.addressEnd.latitude);
      this.getRegeo();
      this.imgList = this.orderInfo.goodsInfo.imgList;

    },
    methods: {
      ...mapActions('m_runner', ['getRunnerInfo']),
      goBack() {
        uni.navigateBack(-1)
        // uni.redirectTo({
        //   url: '/subpkg-runner/runner-rush-order/runner-rush-order'
        // });
      },
      async initData() {
        console.log('init');
        let res = await uniMapCo.initDynamics001({
          pickAddress: this.runnerAddress,
          deliveryAddress: this.addressEnd
        });
        this.refresh();
        console.log(res);
        this.setPolyline(res.polyline);
      },
      // 刷新地图
      async refresh() {
        await this.$refs.map.refresh({
          needIncludePoints: true
        });
        let res = await uniMapCo.getPolyline();
        if (res.end) {
          await this.$refs.map.refresh({
            needIncludePoints: true
          });
          this.stop();
          this.setPolyline([]);
        } else {
          this.setPolyline(res.polyline);
        }
      },
      // 设置路线
      setPolyline(polyline) {
        this.polyline = polyline;
        this.$refs.map.setPolyline(polyline);
      },
      //获取位置信息
      getRegeo() {
        uni.showLoading({
          title: '正在获取定位'
        });
        this.amapPlugin.getRegeo({
          success: (data) => {
            console.log(data)
            this.runnerAddress = {
              name: data[0].name,
              address: data[0].regeocodeData.addressComponent.city,
              latitude: parseFloat(data[0].latitude),
              longitude: parseFloat(data[0].longitude),
            }
            uni.hideLoading()
          },
          fail: (err) => {
            uni.hideLoading();
            uni.showModal({
              title: '提示',
              content: '位置信息获取失败（请确定定位功能是否打开）',
              showCancel: false
            });
          },
        });
      },
      //切换终点
      switchAddress(it) {
        // console.log(it);
        this.addressEnd = {
          latitude: it.latitude,
          longitude: it.longitude,
          name: it.name
        };
        this.initData();
      },
      //导航
      goToNav(it) {
        uni.openLocation({
          latitude: it.latitude,
          longitude: it.longitude,
          scale: 18
        })
      },
      ViewImage(e) {
        uni.previewImage({
          urls: this.imgList,
          current: e.currentTarget.dataset.url
        });
      },
      //更新订单状态
      async updateOrderStatus() {
        const {
          result: res
        } = await db.collection('runner_order').where({
          _id: this.id
        }).update({
          state: '已取货'
        })
        if (res.updated === 1) {
          uni.$showMsg(('取货成功！'));
        }
      },
      async updateOrderFinished() {
        //获取时间
        const currentDateTime = getCurrentDateTime();
        const {
          result: res
        } = await db.collection('runner_order').where({
          _id: this.id
        }).update({
          state: '已送达',
          finished: true,
          finishedTime:currentDateTime
        })
        if (res.updated === 1) {
          this.updateOrderInfo(this.order.orderInfo._id);
          this.addPrice();
          uni.$showMsg(('已送达！'));
          this.getRunnerInfo(this.runnerInfo._id);
          const timeOut = setTimeout(function() {
            clearTimeout(timeOut)
          }, 2000);
          timeOut();
          uni.navigateTo({
            url: '/subpkg-runner/runner-rush-order/runner-rush-order'
          })
        }
      },
      async updateOrderInfo(id) {
        const {
          result: res
        } = await db.collection('my_order').where({
          _id: id
        }).update({
          state: '已完成',
          finished: true
        })
        console.log('orders'.res);
      },
      async addPrice() {
        const mon = this.runnerInfo.money;
        const {
          result: res
        } = await db.collection('my_runner').where({
          _id: this.runnerInfo._id
        }).update({
          money: mon + this.order.orderInfo.price
        })
      }
    },
    computed: {
      ...mapState('m_runner', ['runnerInfo']),
      //地图高度属性
      heightCom() {
        let systemInfo = uni.getSystemInfoSync();
        return `${systemInfo.windowHeight-97}px`;
      },
    },
    watch: {
      runnerAddress: {
        handler: function(newValue, oldValue) {
          if (this.runnerAddress && this.addressEnd) return this.initData()
        },
      },
      addressEnd(newValue, oldValue) {
        if (this.runnerAddress && this.addressEnd) return this.initData()
      },
    },
  }
</script>

<style lang="scss">
  .top-navigate {
    z-index: !important;
    position: relative;
    display: flex;
    justify-content: left;
    align-items: center;

    .top-navigate-title {
      margin: 0 5px;
      font-weight: bold;
    }
  }


  .addressInfo {
    width: 100%;
    padding-bottom: 20px;
    background-color: white;
    border-radius: 10px;
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: center;
    flex-direction: column;
    opacity: 0.9;

    .order-detail {
      background-color: #ffffff;
      padding: 1rpx 30rpx;
      display: flex;
      min-height: 100rpx;
      justify-content: space-between;
      flex-direction: column;
      border-bottom: 1px solid #eee;

      .order-detail-title {
        margin: 10px 0;
      }
    }

    .item_box {
      height: 45px;
      display: flex;
      font-size: 16px;
      align-items: center;
      justify-content: space-between;
      line-height: 45px;
      margin: 5px 16px;

      .address {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
</style>